export class BinaryReader {
    private view: DataView;
    private _offset: number;
    public get offset(): number {
        return this._offset;
    }
    public set offset(value: number) {
        this._offset = value;
    }

    get length(): number {
        return this.view.byteLength;
    }

    constructor(buffer: ArrayBuffer) {
        this.view = new DataView(buffer);
        this._offset = 0;
    }

    public readByte(): number {
        const value = this.view.getUint8(this._offset);
        this._offset += 1;
        return value;
    }

    public readInt64(littleEndian: boolean = true): bigint {

        // 获取高位和低位的 32 位整数
        const high = this.view.getInt32( this._offset, littleEndian);
        const low = this.view.getUint32( this._offset + 4, littleEndian);
        this._offset += 8;
        // 将两个 32 位整数组合成一个 64 位整数
        if (littleEndian) {
            return (BigInt(low) << BigInt(32) ) | BigInt(high);
        } else {
            return (BigInt(high) << BigInt(32)) | BigInt(low);
        }
    }

    public readInt32(littleEndian: boolean = true): number {
        const value = this.view.getInt32(this._offset, littleEndian);
        this._offset += 4;
        return value;
    }

    public readInt16(littleEndian: boolean = true): number {
        const value = this.view.getInt16(this._offset, littleEndian);
        this._offset += 2;
        return value;
    }


    public readFloat32(littleEndian: boolean = true): number {
        const value = this.view.getFloat32(this._offset, littleEndian);
        this._offset += 4;
        return value;
    }

    public readBytes(length: number): Uint8Array {
        const value = new Uint8Array(this.view.buffer, this._offset, length);
        this._offset += length;
        return value;
    }
}